<?php

namespace cms\modules\v1\models\shop;
use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class GoodsDetail extends \common\models\shop\GoodsDetail
{

    public function getMultipleInfo($goodsId = 0) {
        try {
            $id = (int) $goodsId;
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['goods_id'] = $id;
            $info = static::getObjectByWhere($where)->with('banner')->asArray()->all();

            $result = [];
            if (!empty($info)) {
                foreach ($info as $k => $v) {
                    $banner = [];
                    foreach ($v['banner'] as $kk => $vv) {
                        $banner[] = [
                            'status' => 'finished',
                            'name' => $vv['goods_image'],
                            'url' => $this->imageHost . $vv['goods_image'],
                        ];
                    }
                    $tmp = [
                        'id' => (int) $v['id'],
                        'spec_name' => $v['goods_spec'],
                        'price' => floatval($v['goods_price']),
                        'stock' => (int) $v['goods_stock'],
                        'need_vip' => $v['need_vip'],
                        'supplier_price' => floatval($v['supplier_price']),
                        'banners' => $banner
                    ];
                    $result[] = $tmp;
                }
            }

            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 添加或修改项目信息
     * @return array
     */
    public function saveMultipleInfo() {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $post = \Yii::$app->request->post();

            $goodsId = (int) $post['id'];
            $detailData = isset($post['data']) ? $post['data'] : [];

            if (empty($goodsId)) {
                throw new Exception('未知主体商品信息');
            }

            $list = static::getByWhere(['goods_id' => $goodsId]);
            $detailIds = ArrayHelper::getColumn($list,'id');
            $postDetailIds = ArrayHelper::getColumn($detailData,'id');

            //1.取出移除掉的ID 差集
            $diffIds = array_diff($detailIds,$postDetailIds);
            //先删除
            if(!empty($diffIds)) {
                if (static::getCountByWhere(['id' => $diffIds]) > 0) {
                    $resDelete = static::deleteAll(['id' => $diffIds]);
                    if (!$resDelete) {
                        throw new Exception('操作失败');
                    }
                }
            }

            //2.添加修改
            if (!empty($detailData)) {
                foreach ($detailData as $k => $v) {
                    $data = [];
                    $data['goods_id'] = $post['id'];
                    $data['goods_spec'] = $v['spec_name'];
                    $data['goods_price'] = $v['price'];
                    $data['goods_stock'] = $v['stock'];
                    $data['id'] = $v['id'];
                    $this->saveSingleDetail($data, $v['banners']);
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function saveSingleDetail($data = [], $banners = []) {
        if (empty($data['goods_spec'])) {
            throw new Exception('未知规格信息');
        }

        if (empty($data['goods_price'])) {
            throw new Exception('未知价格信息');
        }
        $data['goods_id'] = (int) $data['goods_id'];
        if (empty($data['goods_id'])) {
            throw new Exception('未知主商品信息');
        }

        $data['goods_price'] = (double) $data['goods_price'];
        $data['goods_stock'] = (int) $data['goods_stock'];
        $id = (int) $data['id'];
        if (!empty($id)) {
            $data['update_time'] = date('Y-m-d H:i:s');
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥');
            }
        } else {
            $data['create_time'] = date('Y-m-d H:i:s');
            $id = static::insertDataWithLog($data);
            if ($id === false) {
                throw new Exception('系统错误，请联系开发小哥哥');
            }
        }
        //存储图片
        (new GoodsBanner())->saveBannerByGoodsDetailId($id, $banners);
    }


    public function getMapForSelect($goodsId = 0) {
        $where['goods_id'] = $goodsId;
        $details = static::getByWhere($where);

        $result = [];
        foreach ($details as $k => $v) {
            $result[] = [
                "id" => $v['id'],
                "name" => $v['goods_spec']
            ];
        }
        return Functions::formatRestAPI(0, '', $result);
    }

}
